#!/usr/bin/python
# -*- coding: UTF-8 -*-
import csv
import pandas as pd
import codecs
import matplotlib.pyplot as plt
import numpy as np
from ZIndex.tool import Util


def genImage(filename, xlabels, ylabels, title=None):
    # 列顺序为 date,code,code_name,close,BOLL_S,LB_S,OBV_S,KDJ_S,WR_S,MFI_S,MACD_S,sum,LB,换手率,涨跌幅,修正涨跌幅
    # xlabels 指定第几行为横坐标
    # ylables 指定第几行为纵坐标
    # 指定跳过前几行skiprows， df.columns获取到列名，df.columns[0,1,2,3....N]获取第0+1列的名字
    df = pd.read_csv(filename, skiprows=10)
    # 用来正常显示中文标签
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    fig = plt.figure(1, figsize=(15, 7))
    title = df.columns[xlabels] + "--" + df.columns[ylabels]
    plt.title(title, fontsize=12)
    # plt.xlabel(df.columns[xlabels])
    plt.ylabel(df.columns[ylabels])
    plt.xticks(rotation=60)
    plt.gcf().subplots_adjust(bottom=0.2)
    bar_width = 0.8
    # plt.bar(labels, values, bottom= 1,color = "SkyBlue")
    plt.bar(df[df.columns[xlabels]], df[df.columns[ylabels]], color='steelblue', alpha=0.8, width=bar_width)

    figname = filename[0:(filename.rfind('/') + 1)] + title + ".png"

    # 删除文件
    Util.deleteFile(title + ".png")
    plt.savefig(figname)
    # plt.show()
    plt.close()
    return figname



def genDFImage(df, xlabels, ylabels, filename, title=None):
    # 列顺序为 date,code,code_name,close,BOLL_S,LB_S,OBV_S,KDJ_S,WR_S,MFI_S,MACD_S,sum,LB,换手率,涨跌幅,修正涨跌幅
    # xlabels 指定第几行为横坐标
    # ylables 指定第几行为纵坐标
    # 指定跳过前几行skiprows， df.columns获取到列名，df.columns[0,1,2,3....N]获取第0+1列的名字
    # df = pd.read_csv(filename, skiprows=9)
    # 用来正常显示中文标签
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    fig = plt.figure(1, figsize=(15, 7))
    # title = df.columns[xlabels] + "--" + df.columns[ylabels]
    title = xlabels + "--" + ylabels
    plt.title(title, fontsize=12)
    # plt.xlabel(df.columns[xlabels])
    plt.ylabel(ylabels)
    plt.xticks(rotation=60)
    plt.gcf().subplots_adjust(bottom=0.2)
    bar_width = 0.8
    # plt.bar(labels, values, bottom= 1,color = "SkyBlue")
    # plt.bar(df[df.columns[xlabels]], df[df.columns[ylabels]], color='steelblue', alpha=0.8, width=bar_width)
    plt.bar(df[xlabels], df[ylabels], color='steelblue', alpha=0.8, width=bar_width)

    figname = filename[0:(filename.rfind('/') + 1)] + title + ".png"

    # 删除文件
    Util.deleteFile('\\result\\' + title + ".png")
    plt.savefig(figname)
    # plt.show()
    plt.close()
    return figname


# 单柱
def genStockDFImage(df, xlabels, ylabels, filename, title=None):

    # 用来正常显示中文标签
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    fig = plt.figure(1, figsize=(15, 7))
    # title = df.columns[xlabels] + "--" + df.columns[ylabels]
    title = xlabels + "--" + ylabels
    plt.title(title, fontsize=12)
    # plt.xlabel(df.columns[xlabels])
    plt.ylabel(ylabels)
    plt.xticks(rotation=60)
    plt.gcf().subplots_adjust(bottom=0.2)
    bar_width = 0.8
    # plt.bar(labels, values, bottom= 1,color = "SkyBlue")
    # plt.bar(df[df.columns[xlabels]], df[df.columns[ylabels]], color='steelblue', alpha=0.8, width=bar_width)
    plt.bar(df['date'], df[ylabels], color='steelblue', alpha=0.8, width=bar_width)

    figname = filename[0:(filename.rfind('/') + 1)] + title + ".png"
    # 删除文件
    Util.deleteFile('\\result\\' + title + ".png")
    plt.savefig(figname)
    plt.close()
    # plt.show()
    return figname


# 双柱
def genStockDFImage2(df, xlabels, ylabels, ylabels2, filename, title=None):

    # 用来正常显示中文标签
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    fig = plt.figure(1, figsize=(15, 7))
    title = xlabels + "--" + ylabels + "--" + ylabels2
    plt.title(title, fontsize=12)
    plt.ylabel(ylabels)
    plt.xticks(rotation=60)
    plt.gcf().subplots_adjust(bottom=0.2)

    x = np.arange(len(df['date']))
    total_width, n = 0.8, 2 # 柱状图总宽度，有几组数据
    width = total_width/n # 单个柱状图的宽度
    x1 = x - width / 2  # 第一组数据柱状图横坐标起始位置
    x2 = x1 + width  # 第二组数据柱状图横坐标起始位置

    plt.bar(x1, df[ylabels], width=width, label=ylabels)
    plt.bar(x2, df[ylabels2],width=width, label=ylabels2)
    plt.xticks(x, df['date'])

    plt.legend()
    figname = filename[0:(filename.rfind('/') + 1)] + title + ".png"
    # 删除文件
    Util.deleteFile('\\result\\' + title + ".png")
    plt.savefig(figname)
    plt.close()
    # plt.show()
    return figname


# 双柱+拆线
def genStockDFImage3(df, xlabels, ylabels, ylabels2, ylabel3, filename, title=None):

    # 用来正常显示中文标签
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False


    labelFont = {'family': 'sans-serif',
                 'weight': 'normal',
                 'size': 4}
    title = xlabels + "--" + ylabels + "--" + ylabels2 + "--" + ylabel3
    x = np.arange(len(df['date']))

    fig, ax1 = plt.subplots()

    total_width, n = 0.8, 2 # 柱状图总宽度，有几组数据
    plt.title(title, fontsize=12)
    ax1.set_ylabel(ylabels)
    ax1.set_xticklabels(df['date'],rotation=60)  # 设置共用的x轴

    # ax1.xticks(rotation=300)
    width = total_width/n # 单个柱状图的宽度
    x1 = x - width / 2  # 第一组数据柱状图横坐标起始位置
    x2 = x1 + width  # 第二组数据柱状图横坐标起始位置
    # ax1.spines["bottom"].set_position(("data", 0))

    ax1.bar(x1, df[ylabels], width=width, label=ylabels)
    ax1.bar(x2, df[ylabels2],width=width, label=ylabels2)
    # ax1.xticks(x, df['date'])

    ax2 = ax1.twinx()
    ax2.set_ylim(0, (df[ylabel3].max() * 1.1))
    ax2.set_ylabel(ylabel3)
    ax2.plot(df['date'], df[ylabel3],color = 'red', label='股价')
    fig.tight_layout()  # otherwise the right y-label is slightly clipped

    ax2.legend(loc='upper left')
    ax1.legend(loc='best')
    #plt.legend()
    figname = filename[0:(filename.rfind('/') + 1)] + title + ".png"
    # 删除文件
    Util.deleteFile('\\result\\' + title + ".png")
    plt.savefig(figname)
    plt.close()
    # plt.show()
    return figname